import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { MessageBox } from 'element-ui'

const service = axios.create({
  baseURL: 'http://139.159.189.4:8000/',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    console.log(1)
    if (store.state.user.auth_token) {
      config.headers.Authorization = 'Bearer ' + store.state.user.auth_token
      console.log(2)
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  async error => {
    if (error.response.status === 401) {
      await store.dispatch('user/logout')
      await router.push('/login')
      await MessageBox.alert('请重新登录', '提示', { type: 'warning' })
    } else {
      await MessageBox.alert(error.response.data, '错误提示', { type: 'warning' })
    }
    return Promise.reject(error)
  }
)

export default service
